<template>
  <div  style="padding: 15px;">
    <vxe-toolbar id="warehouseLocationId" :custom="{storage: true}" export :refresh="{query: findList}">
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <el-button v-bind:disabled="printFlag" @click="funcPrint">打印入库单</el-button>

      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      :align="allAlign"
      :export-config='{type:"csv"}'
      show-footer
      highlight-hover-row
      row-id="id"
      class="mytable-footer"
      height="700"
      :loading="loading"
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
      sort-config.remote
      @sort-change="sortList"
      auto-resize
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="status" title="状态" min-width="100" sortable show-header-overflow show-overflow :formatter="formatterStatus"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="warehouseName" title="所属仓库" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseCode" placeholder="请输入所属仓库 " style="width:100%" clearable>
            <el-option
              v-for="item in warehouseData"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="shipmentName" title="入驻商" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.shipmentName" clearable filterable placeholder="请选择入驻商">
            <el-option
              v-for="item in options"
              :key="item.partyCode"
              :label="item.userName"
              :value="item.userName">
            </el-option>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="code" title="入库单号" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.code" placeholder="请输入入库单号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="sourceCode" title="来源单号" min-width="200" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.sourceCode" placeholder="请输入来源单号" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="typeText" title="单据类型" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.type" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in typeList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="createdName" title="创建人" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.createdName" placeholder="请输入创建人" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="gmtCreated" title="创建时间" min-width="400" sortable show-header-overflow show-overflow />
        <template v-slot:header="{ column }">
            <el-date-picker
              v-model="listQuery.gmtCreatedRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              style="width:100%"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="value => changeDate(value, 'gmtCreated')"
            />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="modifiedName" title="修改人" min-width="150" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.modifiedName" placeholder="请输入修改人" clearable />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="gmtModified" title="修改时间" min-width="400" sortable />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="listQuery.gmtModifiedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtModified')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="150">
        <template slot-scope="scope">
          <el-tooltip  effect="dark" content="查看" placement="top">
            <vxe-button type="text" @click="funcDetail(scope.row.code)">
              <i class="el-icon-document" />
            </vxe-button>
          </el-tooltip>

        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />
    <vxe-modal v-model="modelPrintFlag" title="打印" width="900" height="800" resize>
      <compPrint ref="printRef" @fatherPrintMethod="fatherPrint"/>
    </vxe-modal>
  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
import compPrint from './components/print.vue'
// import compEdit from './components/brandEdit.vue'
// import compDetail from './components/brandDetail.vue'
import request from '@/utils/request'
import { inboundList } from '@/api/inStorage'
import { getWarehouse } from '@/api/basicInfo'
import { shipments } from "@/api/outStorage";
export default {
  name: '入库管理',
  components: {
    compPrint
  },
  data() {
    return {
      message: '',
      // 日期选项
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      initFinishFlag: false,
      modelPrintFlag:false, //打印开关
      loading: false,
      allAlign: 'center',
      tableData: [],
      modelAddFlag: false,
      modelbindingFlag:false,
      modelEditFlag: false,
      statusList:[                       //状态
        { code: "0", name: "入库完成" },
      ],
      typeList: [
        {code: "0", name: "采购入库"},
        {code: "1", name: "退货入库"},
        {code: "2", name: "盘盈入库"},
        {code: "3", name: "调拨入库"},
        {code: "4", name: "期初入库"}
      ],
      warehouseData:[],

      modelDetailFlag: false,
      copy: false,
      listQuery: {
        total: 0,             //总数
        createdName:'',         //创建人
        modifiedName:'',        //修改人
        gmtCreated:'',        //创建时间
        gmtModified:'',       //修改时间
        code:'',                                  //入库单号 ,
        gmtOrder:'',                                  //订单日期 ,
        inboundQuantity:'',                                  //入库数量 ,
        planQuantity:'',                                  //计划数量 ,
        remarks:'',                                  //备注 ,
        shipmentCode:'',                                  //入驻商 ,
        sourceCode:'',                                  //来源单号 ,
        status:'',                                  //状态 ,
        type:'',                                  //单据类型 ,
        warehouseCode:'',                                  //仓库
        pageNum: 1,
        pageSize: 10,
        sortField: '',
        sortType: '',
      },
      options: []
    }
  },
  created() {
    this.getWarehouse()
    this.$eventBus.$on("refreshList", () => {
      this.findList()
    })
  },
  computed: {
    'printFlag': function() {
      if(this.initFinishFlag) {
        let selectRecords = this.$refs.xTable.getCheckboxRecords();
        if(selectRecords.length > 0) {
          return false;
        } else {
          return true;
        }
      }
      return true;
    }
  },

  methods: {
    // 打印组件的父方法
    fatherPrint() {
      this.modelPrintFlag = false
      this.findList()
    },
    //打印
    funcPrint() {
      let nowDate = new Date();
      let year = nowDate.getFullYear()
      let month = nowDate.getMonth() + 1
      let date = nowDate.getDate()
      let hh =new Date(nowDate).getHours() < 10? "0" + new Date(nowDate).getHours(): new Date(nowDate).getHours();
      let mm =new Date(nowDate).getMinutes() < 10? "0" + new Date(nowDate).getMinutes(): new Date(nowDate).getMinutes();
      let ss =new Date(nowDate).getSeconds() < 10? "0" + new Date(nowDate).getSeconds(): new Date(nowDate).getSeconds();

      if (month >= 1 && month <= 9) {
        month = "0" + month
      }
      if (date >= 0 && date <= 9) {
        date = "0" + date
      }
      let systemDate = year + '-' + month + '-' + date +" "+ hh + ":" + mm + ':' + ss ;
      this.$refs.printRef.date = systemDate
      let selectRecords = this.$refs.xTable.getCheckboxRecords()
      let arr = []
      selectRecords.forEach( i => {
        arr.push(i.code)
      })
      this.$refs.printRef.getInfo(arr)
      this.modelPrintFlag = true
    },
    changeDate(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
        this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
    //仓库查询
    getWarehouse(){
      getWarehouse().then(response => {
        this.warehouseData = response.data
        this.findList()
        this.initFinishFlag = true;

      })
    },
    //获取列表
    findList() {
      this.loading = true
      shipments().then(res => {
        this.options = res.data
      })
      return inboundList(this.listQuery).then(response => {
        this.tableData = response.data.records
        this.listQuery.total = response.data.total
        this.loading = false
      })
    },
    // 排序
    sortList({ column, property, order }) {
    property =  property==='warehouseName' ? 'warehouseCode'
                : property === 'typeText' ? 'type'
                : property;

      if (order) {
        this.listQuery.sortField = property
        this.listQuery.sortType = order
      } else {
        this.listQuery.sortField = ''
      }
      this.findList()
    },
    // 详情方法
    funcDetail(code) {
      this.$router.push({
        path: "/inbound/inboundDetail",
        query: { code: code,}
      });
    },

    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage
      this.listQuery.pageSize = pageSize
      this.findList()
    },
    // 翻译状态
    formatterStatus({ cellValue }) {
      if (cellValue === '0') {
        return '入库完成'
      }
    },

    // 底部颜色设置
   /*  footerCellClassName({ $rowIndex, column, columnIndex }) {
      if (columnIndex === 0) {
        if ($rowIndex === 0) {
          return 'col-blue'
        } else {
          return 'col-red'
        }
      }
    }, */
    // 设置底部合计
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          if (['pageviews', 'forecast'].includes(column.property)) {
            return XEUtils.sum(data, column.property)
          }
          return null
        })
      ]
    },

  },
  destroyed() {
    this.$eventBus.$off('refreshList')
  },
}
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
